package controller

import (
	"gitee.com/saxon134/go-utils/saData/saTime"
	"gitee.com/saxon134/workflow/api"
	"gitee.com/saxon134/workflow/db"
	"gitee.com/saxon134/workflow/db/tag"
	"gitee.com/saxon134/workflow/errs"
	"gitee.com/saxon134/workflow/interface/ioTag"
)

func TagList(c *api.Context) (resp *api.Response, err error) {
	in := new(ioTag.ListRequest)
	c.Bind(in)

	var ary = make([]*tag.TblTag, 0, 20)
	var query = db.MySql.Table(tag.TBNTag)
	if in.Keyword != "" {
		query.Where("name like '%?%'", in.Keyword)
	}

	query.Find(&ary)
	return &api.Response{Result: ary}, nil
}

func TagSave(c *api.Context) (resp *api.Response, err error) {
	in := new(tag.TblTag)
	c.Bind(in)

	if in.ProjectId <= 0 || in.Name == "" {
		return nil, errs.New(errs.ErrorParams)
	}

	if in.Id <= 0 {
		in.CreateAt = saTime.Now()
	}

	var existId int64
	db.MySql.Raw("select id from tag where name = ?", in.Name).First(&existId)
	if existId > 0 && existId != in.Id {
		return nil, errs.New(errs.ErrorExisted)
	}

	err = db.MySql.Save(in).Error
	if err != nil {
		return nil, errs.New(err)
	}
	return &api.Response{Result: nil}, nil
}
